//
//  PeripheralViewController.m
//  BlueToothPeripheral
//
//  Created by US bike on 2017/8/4.
//  Copyright © 2017年 US bike. All rights reserved.
//

#import "PeripheralViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "Tools.h"



@interface PeripheralViewController ()<CBPeripheralManagerDelegate>

@property (nonatomic, strong) CBPeripheralManager *peripheralManager;

@property (nonatomic, strong) CBMutableCharacteristic *subscriptCharacteristic;



@property (weak, nonatomic) IBOutlet UITextField *sendTextField;
@property (weak, nonatomic) IBOutlet UITextField *bufferTextField;
@property (weak, nonatomic) IBOutlet UILabel *receiveLbl;
@property (weak, nonatomic) IBOutlet UITextView *logTextView;
@end

@implementation PeripheralViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenAction)];
    [self.view addGestureRecognizer:tap];
    
}


- (void) setupUI {
    self.sendTextField.text = @"我是蓝牙外设发送的消息";
    self.bufferTextField.text = @"我是蓝牙外设设置给中心设备读取的消息";
}



/** 创建服务和特征 */
- (void)setupServiceAndCharacteristics {
    // 创建服务
    CBUUID *serviceID = [CBUUID UUIDWithString:SERVICE_UUID];
    CBMutableService *service = [[CBMutableService alloc] initWithType:serviceID primary:YES];
    // 创建服务中的特征
    CBUUID *characteristicID_Read = [CBUUID UUIDWithString:CHARACTERISTIC_UUID_READ];
    CBMutableCharacteristic *characteristic_read = [
                                                    [CBMutableCharacteristic alloc]
                                                    initWithType:characteristicID_Read
                                                    properties:CBCharacteristicPropertyNotify | CBCharacteristicPropertyRead
                                                    value:nil
                                                    permissions:CBAttributePermissionsReadable
                                                    ];
    
    CBUUID *characteristicID_write = [CBUUID UUIDWithString:CHARACTERISTIC_UUID_WRITE];
    CBMutableCharacteristic *characteristic_write = [
                                                     [CBMutableCharacteristic alloc]
                                                     initWithType:characteristicID_write
                                                     properties:CBCharacteristicPropertyWrite | CBCharacteristicPropertyWriteWithoutResponse
                                                     value:nil
                                                     permissions:CBAttributePermissionsWriteable
                                                     ];
    CBUUID *characteristicID_subscript = [CBUUID UUIDWithString:CHARACTERISTIC_UUID_SUBSCRIPT];
    CBMutableCharacteristic *characteristic_subscript = [[CBMutableCharacteristic alloc]
                                                         initWithType:characteristicID_subscript
                                                        properties:CBCharacteristicPropertyNotify
                                                         value:nil
                                                         permissions:CBAttributePermissionsReadable];

    self.subscriptCharacteristic = characteristic_subscript;
    // 特征添加进服务
    service.characteristics = @[characteristic_read,characteristic_write,characteristic_subscript];
    // 服务加入管理
    [self.peripheralManager addService:service];

    

}

#pragma mark - CBPeripheralManageDelegate


//蓝牙状态发生变化
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {

    [Tools debugLog:@"蓝牙设备状态发生变化" AndTextView:self.logTextView];
    
    switch (peripheral.state) {
        case CBManagerStateUnknown:   //CB中央管理器启动状态
            [Tools debugLog:@"本地蓝牙状态，初始的时候是未知的（刚刚创建的时候）" AndTextView:self.logTextView];

            break;
        case CBManagerStateResetting:
            [Tools debugLog:@"本地蓝牙状态，正在重置状态" AndTextView:self.logTextView];

            break;
        case CBManagerStateUnsupported:
            [Tools debugLog:@"本地蓝牙状态，设备不支持的状态" AndTextView:self.logTextView];

            break;
        case CBManagerStateUnauthorized:
            [Tools debugLog:@"本地蓝牙状态，设备未授权状态" AndTextView:self.logTextView];

            break;
        case CBManagerStatePoweredOff:
            [Tools debugLog:@"本地蓝牙状态，设备关闭状态" AndTextView:self.logTextView];

            break;
        case CBManagerStatePoweredOn:
            [Tools debugLog:@"本地蓝牙状态，设备开启状态 -- 可用状态" AndTextView:self.logTextView];

            
            // 创建Service（服务）和Characteristics（特征）
            [self setupServiceAndCharacteristics];
            // 根据服务的UUID开始广播
            [self.peripheralManager startAdvertising:@{
                                                       CBAdvertisementDataServiceUUIDsKey:@[[CBUUID UUIDWithString:SERVICE_UUID]],
                                                       CBAdvertisementDataLocalNameKey : @"iPhone"}
             ];
            
            break;
        default:
            break;
    }
}


- (void)peripheralManager:(CBPeripheralManager *)peripheral willRestoreState:(NSDictionary<NSString *, id> *)dict {
    
}


- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(nullable NSError *)error {
    
    NSString *logStr;
    if (error) {
        logStr = [NSString stringWithFormat:@"开始广播信息, 广播失败"];
    } else {
        logStr = [NSString stringWithFormat:@"开始广播信息, 广播成功, 蓝牙名字是%@",BLUETOOTH_NAME];
    }
    [Tools debugLog:logStr AndTextView:self.logTextView];
}

- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(nullable NSError *)error {
    
    NSString *logStr;
    if (error) {
        logStr = [NSString stringWithFormat:@"添加服务失败"];
    } else {
        logStr = [NSString stringWithFormat:@"成功添加服务，%@",service.UUID];
    }
    [Tools debugLog:logStr AndTextView:self.logTextView];
}

//中心设备订阅成功
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic {

    NSString *logStr = [NSString stringWithFormat:@"成功订阅特征：%@",characteristic.UUID];
    [Tools debugLog:logStr AndTextView:self.logTextView];

    
}

//中心设备取消订阅
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic {
    
    NSString *logStr = [NSString stringWithFormat:@"成功取消订阅特征：%@",characteristic.UUID];
    
    [Tools debugLog:logStr AndTextView:self.logTextView];
}

//中心设备读
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request {
    // 请求中的数据，这里把文本框中的数据发给中心设备
    
    if ([request.characteristic.UUID.UUIDString isEqualToString:CHARACTERISTIC_UUID_READ]) {
        
        NSString *logStr = [NSString stringWithFormat:@"收到 读特征 读取消息请求，数据为：%@",self.bufferTextField.text];
        [Tools debugLog:logStr AndTextView:self.logTextView];

        request.value = [self.bufferTextField.text dataUsingEncoding:NSUTF8StringEncoding];
        // 成功响应请求
        [peripheral respondToRequest:request withResult:CBATTErrorSuccess];
    }
}

//中心设备写
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray<CBATTRequest *> *)requests {
    // 写入数据的请求
    CBATTRequest *request = requests.lastObject;
    
    if ([request.characteristic.UUID.UUIDString isEqualToString:CHARACTERISTIC_UUID_WRITE]) {

        
        // 把写入的数据显示在文本框中
        NSString *dataStr = [[NSString alloc] initWithData:request.value encoding:NSUTF8StringEncoding];
        
        NSString *logStr = [NSString stringWithFormat:@"收到 写特征 写入的数据请求，数据为：%@",dataStr];
        [Tools debugLog:logStr AndTextView:self.logTextView];

        self.receiveLbl.text = dataStr;
    }
}

- (void)peripheralManagerIsReadyToUpdateSubscribers:(CBPeripheralManager *)peripheral {
    [Tools debugLog:@"peripheralManagerIsReadyToUpdateSubscribers" AndTextView:self.logTextView];

    
}


#pragma mark 点击事件
- (IBAction)senderAction:(id)sender {
    
    if (![self.sendTextField hasText]) {
        [Tools debugLog:@"没有要发送的数据" AndTextView:self.logTextView];
    } else {
        
        BOOL sendSuccess = [self.peripheralManager updateValue:[self.sendTextField.text dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:self.subscriptCharacteristic onSubscribedCentrals:nil];
        
        if (sendSuccess) {
            [Tools debugLog:@"数据发送成功" AndTextView:self.logTextView];

        }else {
            [Tools debugLog:@"数据发送失败" AndTextView:self.logTextView];
        }
    }
    
}

- (IBAction)beginAction:(UIButton *)sender {
    
    if (!_peripheralManager) {
        
        
        _peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
        
        [sender setTitle:@"停止广播" forState:UIControlStateNormal];
    } else {
        [_peripheralManager stopAdvertising];
        _peripheralManager = nil;
        
        [sender setTitle:@"开始广播" forState:UIControlStateNormal];
    }
}


- (void) hiddenAction {
    [self.view endEditing:YES];
}

- (void) dealloc {
    [_peripheralManager stopAdvertising];
    _peripheralManager = nil;
}


@end
